package controller

import (
	"shop/internal/config"
	"shop/internal/model"
	"shop/pkg"
	"strings"

	"github.com/gin-gonic/gin"
)

func QueryGoods(c *gin.Context) {
	var req model.QueryGoodsItem
	if pkg.BindJson(c, &req) {
		return
	}
	db := config.DB.Model(&model.GoodsItem{})
	if strings.TrimSpace(req.GoodsName) != "" {
		db = db.Where("goods_name like ?", "%"+req.GoodsName+"%")
	}
	if req.MinPrice > 0 {
		db = db.Where("price >= ?", req.MinPrice)
	}
	if req.MaxPrice > 0 {
		db = db.Where("price <= ?", req.MaxPrice)
	}
	if req.Status != 0 {
		db = db.Where("status = ?", req.Status)

	}
	var goods []model.GoodsItem
	var total int64
	db.Count(&total)
	if req.PageNum < 1 {
		req.PageNum = 1
	}
	if req.PageSize < 1 {
		req.PageSize = 10
	}
	db = db.Offset(req.PageNum - 1*req.PageSize).Limit(req.PageSize)
	if err := db.Find(&goods).Error; err != nil {
		c.JSON(500, gin.H{"msg": err.Error()})
		return
	}
	if len(goods) == 0 {
		c.JSON(200, gin.H{"msg": "查询成功", "data": []model.GoodsItem{}})
	}

}
func AddGoods(c *gin.Context) {
	var req model.GoodsItem
	if pkg.BindJson(c, &req) {
		return
	}
	if err := config.DB.Create(&req).Error; err != nil {
		c.JSON(500, gin.H{"msg": err.Error()})
		return
	}
	c.JSON(200, gin.H{"msg": "添加成功", "status": 200})
}

func UpdateGoods(c *gin.Context) {

	pkg.SmartUpdate(config.DB, c, &model.GoodsItem{}, "goods_id")

}
